package com.aco.party.web.validator.system;

import com.aco.party.model.po.User;
import com.aco.party.service.system.UserService;
import com.aco.party.util.SpringContextUtil;
import com.aco.party.web.command.system.SignupCommand;
import org.springframework.util.StringUtils;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import java.util.regex.Pattern;

/**
 * Created by flying on 4/26/2016 0026.
 */
public class EditForgetPwdValidator implements Validator {
    private static final String SIMPLE_EMAIL_REGEX = "[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}";

    public boolean supports(Class aClass) {
        return SignupCommand.class.isAssignableFrom(aClass);
    }

    public void validate(Object o, Errors errors) {
        SignupCommand command = (SignupCommand)o;
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "username", "error.username.empty", "请输入用户名");

        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "email", "error.email.empty", "请输入邮箱地址");
        if( StringUtils.hasText(command.getEmail()) && !Pattern.matches(SIMPLE_EMAIL_REGEX, command.getEmail().toUpperCase()) ) {
            errors.rejectValue("email", "error.email.invalid", "Please enter a valid email address.");
        }

        UserService userService = (UserService) SpringContextUtil.getBean("userService");
        User user = userService.findUserByName(command.getUsername());
        if(user == null){
            errors.reject("username","该用户名不存在！请重新填写！");
        }else{
            if(!command.getEmail().equals(user.getEmail())){
                errors.reject("username and email not in a pair","用户名和邮箱不匹配！");
            }
        }
    }
}
